// utils/response.ts
import { Response } from 'express';
export interface ApiResponse<T = any> {
    code: number;        // 业务状态码
    message: string;     // 响应信息
    data?: T;           // 响应数据
    timestamp: number;   // 时间戳
    success: boolean;    // 是否成功
}

export interface PaginationData<T> {
    list: T[];
    total: number;
    page: number;
    pageSize: number;
}

export interface ApiError {
    code: number;
    message: string;
    details?: any;
}

export class ResponseUtil {
    static success<T>(
        res: Response,
        data?: T,
        message: string = '操作成功',
        code: number = 200
    ) {
        const response: ApiResponse<T> = {
            code,
            message,
            data,
            timestamp: Date.now(),
            success: true
        };
        return res.status(200).json(response);
    }

    /**
     * 分页成功响应
     */
    static successWithPagination<T>(
        res: Response,
        list: T[],
        total: number,
        page: number,
        pageSize: number,
        message: string = '查询成功'
    ) {
        const paginationData: PaginationData<T> = {
            list,
            total,
            page,
            pageSize
        };
        return this.success(res, paginationData, message);
    }

    /**
     * 失败响应
     */
    static error(
        res: Response,
        message: string = '操作失败',
        code: number = 500,
        data?: any,
        httpStatus: number = 400
    ) {
        const response: ApiResponse = {
            code,
            message,
            data,
            timestamp: Date.now(),
            success: false
        };
        return res.status(httpStatus).json(response);
    }

    /**
     * 参数错误
     */
    static badRequest(res: Response, message: string = '参数错误', data?: any) {
        return this.error(res, message, 400, data, 400);
    }

    /**
     * 未授权
     */
    static unauthorized(res: Response, message: string = '未授权访问') {
        return this.error(res, message, 401, null, 401);
    }

    /**
     * 禁止访问
     */
    static forbidden(res: Response, message: string = '禁止访问') {
        return this.error(res, message, 403, null, 403);
    }

    /**
     * 资源不存在
     */
    static notFound(res: Response, message: string = '资源不存在') {
        return this.error(res, message, 404, null, 404);
    }

    /**
     * 服务器内部错误
     */
    static internalError(res: Response, message: string = '服务器内部错误') {
        return this.error(res, message, 500, null, 500);
    }
}